<?php
/*
 *   Pmail easy way to send emails
 *   Copyright (C) 2009  Felipe Theodoro Gonçalves (www.ftgoncalves.com)
 *
 *   This program is free software: you can redistribute it and/or modify
 *	 it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
class GroupsController extends PmailAppController {

	public $uses = array('Pmail.Group', 'Pmail.Member');
	public $components = array('Session');

	public function beforeFilter(){

		$this->set('page', 'groups');

	}

	public function index(){

		$groups = $this->Group->find('all', array(
			'fields' => array('Group.id', 'Group.name', 'Group.created')
		));
		$this->set('groups', $groups);

		$this->render();

	}

	public function set_new_group(){

		if($this->data and !empty($this->data['name'])){

			$this->Group->set($this->data);
			$this->Group->save();
			$this->Session->setFlash(__d('pmail', 'Group saved successfully', true), 'default', array(), 'sucesso');
			$this->redirect('/pmail/groups/index');

		}else{

			$this->Session->setFlash(__d('pmail', 'It is necessary to fill in all fields', true), 'default', array(), 'erro');
			$this->redirect('/pmail/groups/index');

		}
	}

	public function insert_member_of_group(){

		if(isset($this->data) and !empty($this->data['pmail_groups_id'])){

			$this->data['members'] = trim($this->data['members']);

			$aux = $this->data['members'];

			if($aux[strlen($aux) -1] != ';'){

				$this->data['members'] = $this->data['members'] . ';';

			}


			$members = explode(';', $this->data['members']);

			if(empty($members[count($members)])){

					array_pop($members);

			}

			foreach($members as $attr => $member){

				$var[] = explode('=', $member);

				if(!array_key_exists(1, $var[$attr])){

					$name = explode('@',$var[$attr][0]);
					$var[$attr][1] = $name[0];

				}

			}

			$id_group = $this->data['pmail_groups_id'];

			$this->data = array();

			foreach($var as $attr => $member){

				$this->data['pmail_groups_id'] = $id_group;
				$this->data['name'] = trim($member[0]);
				$this->data['email'] = trim($member[1]);
				$this->Member->create($this->data);
				$this->Member->save();
				$this->data = array();

			}

			$this->Session->setFlash(__d('pmail', 'Members added successfully: Total = ' . ($attr + 1), true), 'default', array(), 'sucesso');
			$this->redirect('/pmail/groups/index');

		}else{

			$this->Session->setFlash(__d('pmail', 'It is necessary to fill in all fields', true), 'default', array(), 'erro');
			$this->redirect('/pmail/groups/add_members');

		}

	}

	public function delete_group($id = null){

		if($id != null){

			$conditons = array(
				'Member.pmail_groups_id = ' . $id
			);

			$this->Member->deleteAll($conditons);
			$this->Group->del($id);
			$this->Session->setFlash(__d('pmail', 'Group deleted successfully', true), 'default', array(), 'sucesso');
			$this->redirect('/pmail/groups/index');

		}

		$this->Session->setFlash(__d('pmail', 'You must select a group to perform this function', true), 'default', array(), 'erro');
		$this->redirect('/pmail/groups/index');

	}

	public function add_group(){

		$this->render();

	}

	public function add_members(){

		$groups = $this->Group->find('list', array(
			'fields' => array('Group.name')
		));

		$this->set('groups', $groups);
		$this->render();

	}

	public function edit_group($id = null){

		$group = $this->Group->find('all', array(
			'conditions' => 'Group.id = ' . $id,
			'fields' => array('Group.name', 'Group.description')
		));

		$this->data = $group[0];
		$this->set('name', $group);

		$members = $this->Member->find('all', array(
			'conditions' => 'Member.pmail_groups_id = ' . $id,
			'fields' => array('Member.id','Member.name', 'Member.email')
		));

		$this->set('members', $members);
		$this->render();
	}

	public function delete_member($id = null){

		if($id != null){

			$this->Member->del($id);
			$this->Session->setFlash(__d('pmail', 'Member deleted successfully', true), 'default', array(), 'sucesso');
			$this->redirect($this->referer());

		}else{

			$this->Session->setFlash(__d('pmail', 'You must select a member to perform this function', true), 'default', array(), 'erro');
			$this->redirect('/pmail/groups/index');

		}

	}

	public function edit_member($id = null){

		if($id != null){

			if($this->data['Member']){

				$this->Member->id = $id;
				$this->Member->set($this->data);
				$this->Member->save();
				$this->Session->setFlash(__d('pmail', 'Data changed', true), 'default', array(), 'sucesso');
				$this->redirect('/pmail/groups/index');

			}else{

				$member = $this->Member->find('first', array(
					'conditions' => array('Member.id' => $id)
				));

				$this->data = $member;
				$this->render();

			}

		}else{

			$this->Session->setFlash(__d('pmail', 'You must select a member to perform this function', true), 'default', array(), 'erro');
			$this->redirect($this->referer());

		}

	}

	public function edit_name_group($id = null){

		if($this->data){

			if($id != null){

				$this->Group->id = $id;
				$this->Group->set($this->data);
				$this->Group->save();
				$this->Session->setFlash(__d('pmail', 'Data from the group successfully changed', true), 'default', array(), 'sucesso');
				$this->redirect($this->referer());

			}else{

				$this->Session->setFlash(__d('pmail', 'You must select a group to perform this function', true), 'default', array(), 'erro');
				$this->redirect($this->referer());

			}

		}else{

			$this->Session->setFlash(__d('pmail', 'You must select a group to perform this function', true), 'default', array(), 'erro');
			$this->redirect($this->referer());

		}

	}

	/**
	 * Cria os menus automatico
	 *
	 */
	public function menu(){

		$this->layout = 'blank';
		Configure::write('debug', 0);

		$links = array(
			'See groups configured' => array('plugin' => 'pmail', 'controller' => 'groups', 'action' => 'index'),
			'Create a new group' => array('plugin' => 'pmail', 'controller' => 'groups', 'action' => 'add_group'),
			'Insert members' => array('plugin' => 'pmail', 'controller' => 'groups', 'action' => 'add_members')
		);

		$this->set('links', $links);
		$this->render('menu/menu');

	}

	/**
	 * Import member via csv
	 *
	 */
	public function import_members($id_group = null){

		if(isset($this->data)){

			if($id_group){

				$doc = $this->data['Pmail'];

				if($doc['file']['error'] == 0 && ereg(".csv",$doc['file']['name'])){

					// Open csv
					$fp = @fopen($doc['file']['tmp_name'], "r");

					// The atributs
					$atributos = fgets($fp, $doc['file']['size']);
					$atributos = explode(';', trim($atributos));

					// Get content
					$content = fread($fp, $doc['file']['size']);
					$content = explode(';', trim($content));

					// Close pointer
					fclose($fp);

					$e = 0;
					$members = array();

					for($i = 0;$i < count($content); $i++){

						if(!empty($content[$i])){

							if($i % 2 == 0){

								$members[$e]['pmail_groups_id'] = $id_group;
								$members[$e]['name'] = trim($content[$i]);

							}else{

								$members[$e++]['email'] = trim($content[$i]);

							}

						}

					}

					$aux = array();

					foreach($members as $member){

						$aux[] = $member;

					}

					$members = $aux;

					$this->Member->set($members);
					$this->Member->saveAll();
					$this->Session->setFlash(__d('pmail', 'Successfully imported', true), 'default', array(), 'sucesso');
					$this->redirect($this->referer());

				}else{

					$this->Session->setFlash(__d('pmail', 'Error trying to upload the csv file, check if the file is valid', true), 'default', array(), 'erro');
					$this->redirect($this->referer());

				}

			}

		}

	}

}